#!/usr/bin/env bash
SCRIPT_BASE_DIR=$( dirname "${BASH_SOURCE[0]}" )
source "${SCRIPT_BASE_DIR}/common/fs_utils.sh"

set -e

function usage() {
  echo "Usage:$( basename $0 ) [-p <dir-prefix> -m <float-model-path> | -s <start> | -t <step> | -n <node-name> | -h]"
  echo -e "\t调用compare_tool.py, 输出其指定算子的MRE等值"
  echo -e "\t-p <dir-prefix>: 量化保存路径的前缀, <dir-prefix>_<per>应该是实际路径"
  echo -e "\t-m <float-model-path> : onnx浮点模型路径"
  echo -e "\t-n <node-name> : onnx模型算子名称"
  echo -e "\t-s <start> : 命令行-per的开始值, default 0.8"
  echo -e "\t-e <end> : 命令行-per的结束值, default 1.0"
  echo -e "\t-t <step> : 每次量化-per值增加一个步长, default 0.001"
  echo -e "\t-h 输出此信息"
  exit 1
}

per=0.8
end=1.0
step=0.001
while getopts "p:m:n:s:e:t:h" arg
do
  case $arg in
    p)
      dirPrefix=$OPTARG
      ;;
    m)
      floatModel=$OPTARG
      ;;
    n)
      nodeName=$OPTARG
      ;;
    s)
      per=$OPTARG
      ;;
    e)
      end=$OPTARG
      ;;
    t)
      step=$OPTARG
      ;;
    *)
      usage
      ;;
  esac
done

if [ -z "${dirPrefix}" -o -z "${floatModel}" -o -z "${nodeName}" ]
then
  echo "-p <dir-prefix> and -m <model-file-name>, -n <node-name> is required"
  exit 1
fi

file_exists_or_die "${floatModel}"

# 计算要执行命令的次数，bash循环测试命令只能用整数
cnt=$( echo "(${end} - ${per}) / ${step}" | bc )

idx=0
while [ ${idx} -le ${cnt} ]
do
  saveDir="${dirPrefix}_${per}"
  dir_exists_or_die ${saveDir}

  r=$( ./tools/compare_tool.py -d ${saveDir} -bn 0 | grep features_1_block_2_0 )
  echo -e "${per}\t${r}"

  per=$( echo ${per} + ${step} | bc )  
  idx=$(( ${idx} + 1 ))
done
